package cn.lblbc.mcdonalds.module.order.list

import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import cn.lblbc.lib.utils.launch
import cn.lblbc.lib.utils.showDeleteDialog
import cn.lblbc.lib.view.LblRecyclerView
import cn.lblbc.mcdonalds.R
import cn.lblbc.mcdonalds.module.order.detail.OrderDetailActivity
import cn.lblbc.mcdonalds.network.NetworkRepository
import cn.lblbc.mcdonalds.network.OrderInfo
import cn.lblbc.mcdonalds.utils.EXTRA_KEY_ORDER_ID
import cn.lblbc.mcdonalds.utils.calcSum1
import kotlinx.android.synthetic.main.activity_order_list.*
import kotlinx.android.synthetic.main.item_order.view.*

/**
 * 厦门大学计算机专业 | 前华为工程师
 * 专注《零基础学编程系列》  http://lblbc.cn/blog
 * 包含：Java | 安卓 | 前端 | Flutter | iOS | 小程序 | 鸿蒙
 * 公众号：蓝不蓝编程
 */
class OrderListActivity : AppCompatActivity() {
    private lateinit var mLblRecyclerView: LblRecyclerView<OrderInfo>
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_order_list)
        initListeners()
        initViews()
    }

    private fun initListeners() {
        toolbar.setOnClickListener { finish() }
    }

    private fun initViews() {
        mLblRecyclerView = lblRecyclerView as LblRecyclerView<OrderInfo>
        mLblRecyclerView.setLayoutResId { R.layout.item_order }
        mLblRecyclerView.setOnBind { itemView, data ->
            itemView.goodsCountTv.text = "共" + data.list.size + "件"
            itemView.moneyTv.text = calcSum1(data.list)
            itemView.orderListView.setData(data.list)
            itemView.deleteOrderTv.setOnClickListener { onDeleteBtnClick(data.orderId) }
        }
        mLblRecyclerView.setOnItemClick { onItemClick(it) }
    }

    private fun onItemClick(it: OrderInfo) {
        val intent = Intent(this, OrderDetailActivity::class.java)
        intent.putExtra(EXTRA_KEY_ORDER_ID, it.orderId)
        startActivity(intent)
    }

    private fun onDeleteBtnClick(orderId: String) {
        val content = "确认删除当前订单么？"
        showDeleteDialog(content) { deleteOrder(orderId) }
    }

    private fun deleteOrder(orderId: String) {
        launch(
            action = { NetworkRepository.apiService.deleteOrder(orderId) },
            onSuccess = { queryData() }
        )
    }

    override fun onResume() {
        super.onResume()
        queryData()
    }

    private fun queryData() {
        launch(
            action = { NetworkRepository.apiService.queryOrderByStatus("0") },
            onSuccess = { it?.data?.let { data -> processResponse(data) } }
        )
    }

    private fun processResponse(data: List<OrderInfo>) {
        mLblRecyclerView.setData(data)
    }
}